import React,{useState,ChangeEvent} from 'react';
import useInput from '../../hooks/useInput';
import style from './create.module.css';

interface optionsItem{
    value:string
}

const initOptions = function(count:number):optionsItem[]{
    let res = [];
    for(let i = 0;i<count;i++){
        res.push({
            value:''
        })
    }
    return res
}

const Create:React.FC = function(){
    let title = useInput('');
    
    let info = useInput('');
    const [options,setOptions] = useState(initOptions(2));

    const addOptionsHandle = () => {
        options.push({
            value:''
        })
        setOptions([...options])
    }

    const disOptionsHandle = (key:number) => {
        if(options.length <= 2){
            return;
        }
        options.splice(key,1);
        setOptions([...options]);
    }


    const handleInput = (key:number,e:ChangeEvent) => {
        options[key].value = (e.target as HTMLInputElement).value;
        setOptions([...options])
    }

    return <form>
        <input type="text" {...title} placeholder="投票标题"/>
        <input type="text" {...info} placeholder="补充描述（选填）"/>
        <ul>
            {
                options.map((item,key) => {
                    return <li key={key}>
                        <span className={style.disBtn} onClick={disOptionsHandle.bind(null,key)}>-</span>
                        <input type="text" value={item.value} onChange={handleInput.bind(null,key)}/>
                    </li>
                })
            }
            {
                options.length < 6 && <li onClick={addOptionsHandle}>
                    <span  className={style.addBtn}>+</span>添加选项
                </li>
            }
        </ul>

    </form>
}

export default Create